<!--
*@Author: QWP
*@Description: 通讯录编辑
*@Date: 2024-07-08 17:04:38
-->
<template>
  <u-dialog v-bind="$attrs" 
    :confirmLoading="loading" 
    destroyOnClose 
    @close="dialogClose" 
    @submit="submit">
    <a-layout class="f-h-100">
      <a-layout-content class="s-bg-white" style="overflow: auto">
        <u-busi-card title="" :bordered="false" :loading="loading">
          <u-form :elements="formEls" 
            :model="form" 
            :gutter="0" 
            ref="formRef">
          </u-form>
        </u-busi-card>
      </a-layout-content>
    </a-layout>
    <template #footerBefore>
      <a-button type="primary" @click="submit('1')" v-if="!attrs.id">保存并继续新增</a-button>
    </template>
  </u-dialog>
</template>

<script lang='ts' setup>
import { ref, reactive, computed, onMounted, h, useAttrs, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { _IFormEl, _IExtra } from '@/src/components/common/form/interface';
import { FormInstance, FormItemProps } from 'ant-design-vue';
import { fileCols } from '@/common/model/fileCols'
import dayjs from 'dayjs';
import { useLoginStore, useBaseStore } from '@/store'
import * as unitApi from '@/service/system/unit'
import * as deptApi from '@/service/system/dept'
import * as userApi from '@/service/system/user'
import * as linkApi from '@/service/personal/link_book'
import { storeToRefs } from 'pinia';
import { alertC, nullC, messageC } from '@/util/common';
import { cloneDeep } from 'lodash'

// const props = defineProps<{
//   id?: string
// }>()

const route = useRoute()
const attrs = useAttrs()
const { userInfo } = storeToRefs(useLoginStore())
const { DUTY_TYPE, RELATIONSHIP_TYPE, deptUsers, deptData, unitData } = storeToRefs(useBaseStore())

const emits = defineEmits(['success'])

const baseData = reactive({
  depts: [],
  users: [],
  units: []
})

const sexArr = [{ label: '男', value: '1' }, { label: '女', value: '2' }]

const formRef = ref<FormInstance>()
const form = ref<object>({})
const formItemProps: FormItemProps & _IExtra = {
  labelWidth: '110px',
  colon: false
}

const formEls = reactive([
  {
    label: '所属单位', key: 'fkunitid', col: { span: 8, }, element: 'select',
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      options: unitData.value,
      disabled: true,
      fieldNames: { label: 'name', value: 'keyid' }
    }
  },
  {
    label: '所属部门', key: 'fkdeptid', col: { span: 8, }, element: 'select',
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      options: deptData.value,
      fieldNames: { label: 'name', value: 'keyid' },
      onChange: function(val, node) {
        if(!val) {
          form.value.fkLeaderId = ''
          form.value.fkLeaderName = ''
        }
      }
    }
  },
  {
    label: '人员名称', key: 'fkusername', col: { span: 8 }, element: 'input',
    formItemProps: { ...formItemProps, required: true },
  },
  {
    label: '联系电话', key: 'phone', col: { span: 8 }, element: 'input',
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      maxLength: 11,
      showCount: true
    }
  },
  {
    label: '职务', key: 'duty', col: { span: 8 }, element: 'input',
    formItemProps: { ...formItemProps, required: true },
    // componentProps: { options: DUTY_TYPE.value }
  },
  {
    label: '部门领导', key: 'fkLeaderId', col: { span: 8 }, element: 'select',
    formItemProps: { ...formItemProps },
    componentProps: { 
      fieldNames: { label: 'name', value: 'keyid' },
      options: computed(() => {
        let deptInfo = deptUsers.value.find(i => i.keyid == form.value.fkdeptid)
        return deptInfo ? deptInfo['children'] : []
      }),
      onChange: function(val, node) {
      }
    }
  },
  {
    label: '排序号', key: 'orderno', col: { span: 8 }, element: 'number',
    formItemProps: { ...formItemProps, required: true },
    componentProps: { min: 0, precision: 0 }
  },
  {
    label: '紧急联系人', key: 'fkemerusername', col: { span: 8 }, element: 'input',
    formItemProps: { ...formItemProps },
  },
  {
    label: '关系', key: 'relationship', col: { span: 8 }, element: 'select',
    formItemProps: { ...formItemProps },
    componentProps: { options: RELATIONSHIP_TYPE.value, allowClear: true }
  },
  {
    label: '性别', key: 'gender', col: { span: 8 }, element: 'select', hide: computed(() =>  attrs.id != ''),
    formItemProps: { ...formItemProps, required: true },
    componentProps: { options: sexArr, allowClear: true }
  },
  {
    label: '紧急联系电话', key: 'emerphone', col: { span: 8 }, element: 'input',
    formItemProps: { ...formItemProps },
  },
  // { label: '', key: 'fkusername', col: { span: 0 }, element: 'input', },
  // { label: '', key: 'id', col: { span: 0 }, element: 'input', },
  {
    label: '备注', key: 'remark', col: { span: 24 }, element: 'textarea',
    formItemProps: { ...formItemProps, },
    componentProps: {
      maxLeng: 200, showCount: true
    }
  },
])

const loading = ref<boolean>()

// 初始化新增表单数据
const initFormInfo = () => {
  form.value = {
    fkunitid: userInfo.value.unitId,
    fkunitname: userInfo.value.unitName,
    fkdeptid: userInfo.value.deptId,
    fkdeptname: userInfo.value.deptName
  }
}

// 保存
const submit = (type?: string) => {
  alertC("确认保存?", 'confirm').then(async res => {
    const url = attrs.id ? 'update' : 'add';
    loading.value = true;
    try {
      let tForm = cloneDeep(form.value)
      const res = await linkApi[url]({ ...tForm, keyid: nullC(attrs.id) })
      if (res.code == 0) {
        messageC(res.msg, "success");
        if (type == '1') {
          initFormInfo()
        } else {
          emits('success')
          dialogClose()
        }
      }
      else {
        messageC(res.msg, "error");
      }
    } catch (error) { }
    loading.value = false
  })
}

// 回显信息
const echoInfo = async () => {
  loading.value = true
  try {
    const res = await linkApi.query(attrs.id)
    if (res.code == 0) {
      form.value = res.data || {}
    }
  } catch (error) { }
  loading.value = false
}

// 弹窗关闭
const dialogClose = () => {
  formRef.value.form.resetFields();
  initFormInfo()
}

watch(() => attrs.open, (nval, olva) => {
  if (nval == true) {

    if (attrs.id) {
      echoInfo()
    }
    else {
      initFormInfo()
    }
  }
})
</script>

<style lang='scss'></style>